/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SLE_HOST_IMPL_H
#define SLE_HOST_IMPL_H

#include <condition_variable>
#include <mutex>
#include <chrono>
#include "sle_utils_observer_list.h"
#include "i_sle_host.h"
#include "sle_host_interface.h"
#include "sle_host_callback_stub.h"
#include "sle_address_parcel.h"

namespace OHOS {
namespace NearLink {
namespace SleStandard {
class SleHost::SleHostImpl {
public:
    SleHostImpl();
    ~SleHostImpl();
    SleErrorCode CheckOperation();

    class SleHostCallbackStubImpl;
    sptr<SleHostCallbackStubImpl> callbackImpl_ = nullptr;

    sptr<ISleHost> proxy_ = nullptr;
    sptr<IRemoteObject::DeathRecipient> deathRecipient_ = nullptr;
    SleObserverList<SleHostCallback> callbacks_;

    std::condition_variable conditionVariable_;
    bool ready_ = false;
    std::mutex mtx_;
    std::mutex mutexProxy_;
    SleDeviceState state_ = SLE_HOST_STATE_ERROR;

private:
    void GetProxy();
    void ResetService(const wptr<IRemoteObject> &remote);
};

class SleHost::SleHostImpl::SleHostCallbackStubImpl : public SleHostCallbackStub {
public:
    SleHostCallbackStubImpl(SleHost::SleHostImpl &impl) : impl_(impl) {}
    ~SleHostCallbackStubImpl() = default;

    void OnSleStateChange(int32_t state) override
    {
        if (state == SLE_HOST_STATE_ENABLED || state == SLE_HOST_STATE_DISABLED) {
            impl_.state_ = (SleDeviceState)state;
            impl_.ready_ = true;
            impl_.conditionVariable_.notify_one();
        }
        impl_.callbacks_.ForEach([state](std::shared_ptr<SleHostCallback> callback) {
            callback->OnSleStateChange((SleDeviceState)state);
        });

    }

    void OnFlowMonitorEvent(float flow) override
    {
        impl_.callbacks_.ForEach([flow](std::shared_ptr<SleHostCallback> callback) {
            callback->OnFlowMonitorEvent(flow);
        });
    }

private:
    SleHost::SleHostImpl &impl_;
    SLE_DISALLOW_COPY_AND_ASSIGN(SleHostCallbackStubImpl);
};
} // SleStandard
}   // OHOS
}   // NearLink

#endif // SLE_HOST_IMPL_H